var arryList = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];

var PaperModule = function () {
    var editable = function () {
        return {
            init: function () {
                var oTable = $('#modelEditable').dataTable({
                    "lengthMenu": [
                        [10, 15, 20, 50],
                        [10, 15, 20, 50]
                    ],
                    "autoWidth":false,
                    "displayLength": 10,
                    "scrollX": true,
                    "language": {
                        "lengthMenu": "每页 _MENU_ 条记录",
                        "paginate": {
                            "previous": "上一页",
                            "next": "下一页"
                        },
                        "info" : "从 _START_ 到  _END_ 条，总记录为 _TOTAL_ 条",    
                        "infoEmpty" : "记录数为0",
                    },
                    "columnDefs": [
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "<center>-</center>",
						    "targets": [0]
						},
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "<center>-</center>",
						    "targets": [1]
						}, 
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "<center>-</center>",
						    "targets": [2]
						}, 
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "<center>-</center>",
						    "targets": [3]
						}
                    ],
                    "columns": [
                       { "data": "title" },
                       { "data": "unqualified" },
                       { "data": "options" },
                       { "data": "operate" }
                   ],
                   "filter" : false,
                   "processing": false,
                   "serverSide": true,
                   "ajaxSource": ctx + "/question/list",
                   "serverMethod": "post",
                   "fnRowCallback" : function(nRow, aData, displayIndex) {
                	   nRow.children[0].id = aData.id;
                	   var unqualified = aData.unqualified;
                	   if (unqualified == "") {
                		   $('td:eq(1)', nRow).html('无');
                	   }
                	   var options = aData.options;
                	   if (options) {
                		   $('td:eq(2)', nRow).html('多选');
                	   }else{
                		   $('td:eq(2)', nRow).html('单选');
                	   }
                	   $('td:eq(3)', nRow).html('<a class="detail fa fa-bars fa-lg " title="详情" href="javascript:;"></a>&nbsp;&nbsp;&nbsp;<a class="modify fa fa-pencil fa-lg " title="修改" href="javascript:;"></a>&nbsp;&nbsp;&nbsp;<a class="delete fa fa-times-circle-o fa-lg " title="删除" href="javascript:;"></a>');
                       return nRow;
                   },
                   "fnServerData" : function(ajaxSource, dataSet, fnCallback) {
                	   var json = "";
	                   var s;
	                   for (var i = 0; i < dataSet.length; i++) {
	                       s = dataSet[i];
	                   	   if (s.name == 'sEcho') {
	                   		   json = json + '"echo":' + s.value;
		                   } else if (s.name == 'iDisplayStart') {
		                	   json = json + ',"page":' + s.value;
		                   } else if (s.name == 'iDisplayLength') {
		                	   json = json + ',"pageSize":' + s.value;
		                   }
	                   }
	                   json = "{"+json + "}";
                       $.ajax({
                       	   "contentType":"application/json; charset=UTF-8",
                           "dataType" : 'json',
                           "type" : "POST",
                           "url" : ctx + "/question/list",
                           "data" : json,
                           "success" : fnCallback
                       });
                   },
                });
                
                // 试题详情
                $('#modelEditable').on("click", "a.detail", (function (e) {
                	 $("#detail_isMultChoice").html("");
                	 $("#detail_title").html("");
                	 var table = document.getElementById("detail_options_table");
                     var tableLength = table.rows.length;
                     for(var int = 1;int < tableLength;int++) {
                        table.deleteRow(1);
                     }	
                     var nRow = $(this).parents('tr')[0];
                     var id = nRow.children[0].id;
                     json = "{\"id\":\""+id+"\"}";
                     $.ajax({
                     	 type:"post",
                         contentType:"application/json; charset=UTF-8",
                         url: ctx + "/question/detail",
                         data:json,
                         dataType:"json",
                         success: function(msg){
                        	$("#btn_detail_Modal").click();
                         	var data = msg.data;
                         	var code = msg.code;
                         	if(code == 1){
                         		var title = data.question.title;
                         		var opts = data.question.options;
                         		var options = data.optList;
                         		$("#detail_title").html(title);
                         		if(!opts){
                         			$("#detail_isMultChoice").html("否");
                         		}else{
                         			$("#detail_isMultChoice").html("是");
                         		}
                         		for(var i=options.length-1;i>=0;i--){
                         			var isMult = "否";
                         			if(options[i].unqualified == 1){
                         				isMult = "是";
                         			}
                         			var tableStr= "<tr role=\"row\" class=\"odd\"><td style=\"font-size:13px;\"> <center>"+options[i].no+"</center></td>"+
                         			"<td style=\"font-size:13px;\">"+options[i].content+"</td>"+
                         			"<td style=\"font-size:13px;\"><center>"+options[i].score+"</center></td>"+
                         			"<td style=\"font-size:13px;\"><center>"+isMult+"</center></td>"+
                         			"</tr>";
                         			$("#detail_options_table tr:eq(0)").after(tableStr);
                         		}
                         	}else{
                         		bootbox.alert("服务器出错了,查看试题详情失败了!");
                         	}
                         },
                         error: function (msg) {
                         	bootbox.alert("服务器出错了,查看试题详情失败了!");
                         }
                     });
                }));
                // 试题修改
                $('#modelEditable').on("click", "a.modify", (function (e) {
                	 	$("#modity_title").val("");
                	 	$("#question_id").val("");
                	 	var table = document.getElementById("modifyEditable");
	                    var tableLength = table.rows.length;
	                    for(var int = 1;int < tableLength;int++) {
	                       table.deleteRow(1);
	                    }	
	                    var nRow = $(this).parents('tr')[0];
	                    var id = nRow.children[0].id;
	                    json = "{\"id\":\""+id+"\"}";
	                    $.ajax({
	                    	type:"post",
	                        contentType:"application/json; charset=UTF-8",
	                        url: ctx + "/question/detail",
	                        data:json,
	                        dataType:"json",
	                        success: function(msg){
	                        	$("#question_id").val(id);
	                        	$("#btn_modify_Modal").click();
	                        	var data = msg.data;
	                        	var code = msg.code;
	                        	if(code == 1){
	                        		var title = data.question.title;
	                        		var opts = data.question.options;
	                        		var options = data.optList;
	                        		$("#modity_title").val(title);
	                        		if(opts == 1){
	                        			$("#modify_isMultChoice").prop('checked',true);
	                        		}else{
	                        			$("#modify_isMultChoice").prop('checked',false);
	                        		}
	                        		//alert($('#modify_isMultChoice').is(':checked'));
	                        		for(var i=options.length-1;i>=0;i--){
	                        			//拼接分数下拉框
	                        			var optsStr = "";
	                        			var score = options[i].score;
	                        			for(var ii=0;ii<5;ii++){
	                        				var temp = ii*5;
	                        				if(score == temp){
	                        					optsStr = optsStr +"<option selected value=\""+temp+"\">"+temp+"</option>";
	                        				}else{
	                        					optsStr = optsStr +"<option value=\""+temp+"\">"+temp+"</option>";
	                        				}
	                        			}
	                        			//拼接不合格选项下拉框
	                        			var unquaridStr = "";
                        				if(options[i].unqualified == 1){
                        					unquaridStr = "<option value=\"否\">否</option><option selected value=\"是\">是</option>";
                        				}else{
                        					unquaridStr = "<option selected value=\"否\">否</option><option value=\"是\">是</option>";
                        				}
	                        			$("#modifyEditable tr:eq(0)").after("<tr role=\"row\" class=\"odd\"><td> <center>"+options[i].no+"</center></td>"+
	                        					"<td>"+
	                        						"<textarea style=\"resize:none;width:430px;\" id=\"order_id\" name=\"option\" value=\""+options[i].content+"\" placeholder=\"选项\" class=\"form-control\">"+options[i].content+"</textarea>"+
	                        					"</td>"+
	                        					"<td>"+
	                        			           "<select class=\"form-control m-b\" name=\"groupId\" id=\"groupId\">"+optsStr+"</select>"+
	                        			        "</td>"+
	                        					"<td>"+
	                        						"<select class=\"form-control m-b\" name=\"groupId\" id=\"groupId\">"+unquaridStr+"</select>"+
	                        					"</td>"+
	                        					"<td>"+
	                        						"<button type=\"button\" onclick=\"delete_this_modify_row(this)\"; class=\"btn btn-primary\">删除</button>"+
	                        					"</td>"+
	                        			"</tr>");
	                        		}
	                        	}else{
	                        		bootbox.alert("服务器出错了,查询试题失败了!");
	                        	}
	                        },
	                        error: function (msg) {
	                        	bootbox.alert("服务器出错了,查询试题失败!");
	                        }
	                    });
                }));
                // 试题删除
                $('#modelEditable').on("click", "a.delete", (function (e) {
                	 var nRow = $(this).parents('tr')[0];
                     var id = nRow.children[0].id;
                	 $.teninedialog({
                         title:'系统提示',
                         content:'确认删除本道试题?',
                         showCloseButton:false,
                         otherButtons:["确定","取消"],
                         otherButtonStyles:['btn-primary','btn-white'],
                         bootstrapModalOption:{keyboard: true},
                         clickButton:function(sender,modal,index){
                        	 if(index == 0){
                        		 json = "{\"id\":\""+id+"\"}";
                                 $.ajax({
                                 	 type:"post",
                                     contentType:"application/json; charset=UTF-8",
                                     url: ctx + "/question/delete",
                                     data:json,
                                     dataType:"json",
                                     success: function(msg){
                                    	 $.teninedialog({
                                             title:'系统提示',
                                             content:msg.message,
                                             showCloseButton:false,
                                             otherButtons:["确定"],
                                             otherButtonStyles:['btn-primary'],
                                             bootstrapModalOption:{keyboard: true},
                                             clickButton:function(sender,modal,index){
                                             	location.reload();
                                             }
                                         });
                                     },
                                     error: function (msg) {
                                     	bootbox.alert("服务器出错了,删除试题失败了!");
                                     }
                                 });
                        	 }
                        	 $(this).closeDialog(modal); 
                         }
                     });
                }));
                $('#btn_query').click(function(){
                	oTable.fnClearTable();
                });
            }

        };
    }();
    return {
        init: function () {
        	editable.init();
        }
    };
}();
//新增试题按钮
function BtnAddQuestion(){
	var table = document.getElementById("optionEditable");
    var tableLength = table.rows.length;
    for(var int = 1;int < tableLength;int++) {
        table.deleteRow(1);
    }
	$("#myerror").css('display','none');
	$("#title").val("");
}

//修改试题新增一行选项
$("#btn_add_modify_option").click(function(){
	var l =$("#modifyEditable tr").length;
	if(l > 26){
		bootbox.alert("选项数量超出最大限制");
		return;
	}
	$("#modifyEditable tr:eq(0)").after("<tr role=\"row\" class=\"odd\"><td> <center>A</center></td>"+
		"<td>"+
			"<textarea style=\"resize:none;width:430px;\" id=\"order_id\" name=\"option\" value=\"\" placeholder=\"选项\" class=\"form-control\"></textarea>"+
		"</td>"+
		"<td>"+
           "<select class=\"form-control m-b\" name=\"groupId\" id=\"groupId\">"+
                "<option selected value=\"0\">0</option>"+
                "<option value=\"5\">5</option>"+
                "<option value=\"10\">10</option>"+
                "<option value=\"15\">15</option>"+
                "<option value=\"20\">20</option>"+
        	"</select>"+
        "</td>"+
		"<td>"+
			"<select class=\"form-control m-b\" name=\"groupId\" id=\"groupId\">"+
				"<option selected value=\"否\">否</option>"+
                "<option value=\"是\">是</option>"+
        	"</select>"+
		"</td>"+
		"<td>"+
			"<button type=\"button\" onclick=\"delete_this_modify_row(this)\"; class=\"btn btn-primary\">删除</button>"+
		"</td>"+
	"</tr>");
	resetSequenceNum("modifyEditable");
});

//新增试题新增一行选项
$('#btn_add_option').click(function(){
	var l =$("#optionEditable tr").length;
	if(l > 26){
		bootbox.alert("选项数量超出最大限制");
		return;
	}
	$("#optionEditable tr:eq(0)").after("<tr role=\"row\" class=\"odd\"><td> <center>A</center></td>"+
		"<td>"+
			"<textarea style=\"resize:none;width:430px;\" id=\"order_id\" name=\"option\" value=\"\" placeholder=\"选项\" class=\"form-control\"></textarea>"+
		"</td>"+
		"<td>"+
           "<select class=\"form-control m-b\" name=\"groupId\" id=\"groupId\">"+
                "<option selected value=\"0\">0</option>"+
                "<option value=\"5\">5</option>"+
                "<option value=\"10\">10</option>"+
                "<option value=\"15\">15</option>"+
                "<option value=\"20\">20</option>"+
        	"</select>"+
        "</td>"+
		"<td>"+
			"<select class=\"form-control m-b\" name=\"groupId\" id=\"groupId\">"+
				"<option selected value=\"否\">否</option>"+
                "<option value=\"是\">是</option>"+
        	"</select>"+
		"</td>"+
		"<td>"+
			"<button type=\"button\" onclick=\"delete_this_row(this)\"; class=\"btn btn-primary\">删除</button>"+
		"</td>"+
	"</tr>");
	resetSequenceNum("optionEditable");
});

//删除当前行
function delete_this_row(t){
	t.parentNode.parentNode.parentNode.removeChild(t.parentNode.parentNode);
	resetSequenceNum("optionEditable");
}

function delete_this_modify_row(t){
	t.parentNode.parentNode.parentNode.removeChild(t.parentNode.parentNode);
	resetSequenceNum("modifyEditable");
}
//重新设置序号  
function resetSequenceNum(str){  
    var num=0;
    $("#"+str+" tr").each(function(index,dom){  
        if(index!=0){  
            $(dom).find("td").first().html(arryList[num]);  
            num++;  
        }  
    });  
}

//清空表单的值  
function resetValue(){  
    $("input[name='u_username']").val("");  
    $("input[name='u_age']").val("");  
    $("input[name='u_birthday']").val("");  
    $("input[name='u_note']").val("");  
}

var OptionAdd = function () {
	var handleValidation = function() {
            var formAdd = $('#addForm');
            var validator = formAdd.validate({
                focusInvalid: true,
                rules: {
                    title: {
                        required: true
                    }
                },
                messages:{
                    title:{
                      required:"标题不能为空"
                    }
                },
                success: function (label, element) {
                    var icon = $(element).parent('.input-icon').children('i');
                    $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
                    icon.removeClass("fa-warning").addClass("fa-check");
                },
                submitHandler: function (form) {
                	function checkOptions(){
                		var flag = 1;
                		$("#myerror").css('display','none');
                		$("#optionEditable").find("tr").each(function () {
                    		var arrtd = $(this).children();
                    		var con = arrtd.eq(0).text();
                    		var conInput = $.trim(arrtd.eq(1).find("textarea").val());
                    		if(con !="次序" && conInput == ""){
                    			arrtd.eq(1).find("textarea").addClass("error");
                    			$("#myerror").css('display','block');
                    			flag = 0;
                    		}else{
                    			arrtd.eq(1).find("textarea").removeClass("error");
                    		}
                    	});
                		return flag;
                	}
                	if(checkOptions() == 1){
                		AddQuestionReq();
                	}
                }
            });
    }
    return {
        init: function () {
            handleValidation();
        }
    };
}();

//增加试题请求服务器
function AddQuestionReq(){
	var title = $("#title").val();
	var isMulti = 0;
	var flag= $('#MultiChoice').is(':checked');
	if(flag){
		isMulti =1;
	}
	var num = 0;
	$("#optionEditable tr").each(function(index,tritem){
		num = num +1;
	});
	if(num <= 1){
		bootbox.alert("请添加选项");
		return;
	}
	var tableData=new Array();
	trindex = 0;
	$("#optionEditable tr").each(function(index,tritem){
		if($(tritem).find("td").length > 0){
			tableData[trindex]=new Array();
	        $(tritem).find("td").each(function(tdindex,tditem){
	        	if(tdindex == 1){
	        		tableData[trindex][tdindex]=$(tditem).find("textarea").val();
	        	}
	        	else if(tdindex == 2 || tdindex == 3){
	        		tableData[trindex][tdindex]=$(tditem).find("option:selected").val();
	        	}else if(tdindex == 0){
	        		tableData[trindex][tdindex]=$(tditem).text();
	        	}
	        });
	        trindex++;
		}
    });
	$('#btn_add_option').attr('disabled',true);
    var json = "{\"question\":\""+title+"\",\"isMulti\":\""+isMulti+"\",\"options\":\""+tableData+"\"}";
	$.ajax({
		type:"post",
	    contentType:"application/json; charset=UTF-8",
	    url: ctx + "/question/doAdd",
	    data:json,
	    traditional: true,
	    dataType:"json",
	    success: function(msg){
	    	$('#dsimiss_add_relation').click();
	    	$('#btn_add_option').attr('disabled',false);
	    	if(msg.code == 1){
	    		$.teninedialog({
                    title:'系统提示',
                    content:'新增试题成功!',
                    showCloseButton:false,
                    otherButtons:["确定"],
                    otherButtonStyles:['btn-primary'],
                    bootstrapModalOption:{keyboard: true},
                    clickButton:function(sender,modal,index){
                    	location.reload();
                    }
                });
	    	}else{
	    		bootbox.alert("服务器偷了个小懒,新增试题失败了!");
	    	}
	    },
	    error: function (msg) {
	    	$('#btn_add_option').attr('disabled',false);
	    	bootbox.alert("服务器偷了个小懒,新增试题失败了！");
	    }
	});
}


var OptionModify = function () {
	var handleValidation = function() {
            var formAdd = $('#modifyForm');
            var validator = formAdd.validate({
                focusInvalid: true,
                rules: {
                    title: {
                        required: true
                    }
                },
                messages:{
                    title:{
                      required:"标题不能为空"
                    }
                },
                success: function (label, element) {
                    var icon = $(element).parent('.input-icon').children('i');
                    $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
                    icon.removeClass("fa-warning").addClass("fa-check");
                },
                submitHandler: function (form) {
                	function checkOptions(){
                		var flag = 1;
                		$("#modifyerror").css('display','none');
                		$("#modifyEditable").find("tr").each(function () {
                    		var arrtd = $(this).children();
                    		var con = arrtd.eq(0).text();
                    		var conInput = $.trim(arrtd.eq(1).find("textarea").val());
                    		if(con !="次序" && conInput == ""){
                    			arrtd.eq(1).find("textarea").addClass("error");
                    			$("#modifyerror").css('display','block');
                    			flag = 0;
                    		}else{
                    			arrtd.eq(1).find("textarea").removeClass("error");
                    		}
                    	});
                		return flag;
                	}
                	if(checkOptions() == 1){
                		ModifyQuestionReq();
                	}
                }
            });
    }
    return {
        init: function () {
            handleValidation();
        }
    };
}();

//修改试题请求服务器
function ModifyQuestionReq(){
	var title = $("#modity_title").val();
	var isMulti = 0;
	var flag= $('#modify_isMultChoice').is(':checked');
	var questionId = $("#question_id").val();
	if(flag){
		isMulti =1;
	}
	var num = 0;
	$("#modifyEditable tr").each(function(index,tritem){
		num = num +1;
	});
	if(num <= 1){
		bootbox.alert("选项数量不能为0");
		return;
	}
	var tableData=new Array();
	trindex = 0;
	$("#modifyEditable tr").each(function(index,tritem){
		if($(tritem).find("td").length > 0){
			tableData[trindex]=new Array();
	        $(tritem).find("td").each(function(tdindex,tditem){
	        	if(tdindex == 1){
	        		tableData[trindex][tdindex]=$(tditem).find("textarea").val();
	        	}
	        	else if(tdindex == 2 || tdindex == 3){
	        		tableData[trindex][tdindex]=$(tditem).find("option:selected").val();
	        	}else if(tdindex == 0){
	        		tableData[trindex][tdindex]=$(tditem).text();
	        	}
	        });
	        trindex++;
		}
    });
	$('#btn_modify_option').attr('disabled',true);
    var json = "{\"question\":\""+title+"\",\"isMulti\":\""+isMulti+"\",\"options\":\""+tableData+"\",\"questionId\":\""+questionId+"\"}";
	$.ajax({
		type:"post",
	    contentType:"application/json; charset=UTF-8",
	    url: ctx + "/question/modify",
	    data:json,
	    traditional: true,
	    dataType:"json",
	    success: function(msg){
	    	$('#dsimiss_modify_relation').click();
	    	$('#btn_modify_option').attr('disabled',false);
	    	if(msg.code == 1){
	    		$.teninedialog({
                    title:'系统提示',
                    content:'修改试题成功!',
                    showCloseButton:false,
                    otherButtons:["确定"],
                    otherButtonStyles:['btn-primary'],
                    bootstrapModalOption:{keyboard: true},
                    clickButton:function(sender,modal,index){
                    	location.reload();
                    }
                });
	    	}else{
	    		bootbox.alert("服务器偷了个小懒,修改试题失败了!");
	    	}
	    },
	    error: function (msg) {
	    	$('#btn_modify_option').attr('disabled',false);
	    	bootbox.alert("服务器偷了个小懒,修改试题失败了！");
	    }
	});
}